//
//  AddressListViewController.m
//  CommunityApp
//
//  Created by 秦乾龙 on 16/12/16.
//  Copyright © 2016年 秦乾龙. All rights reserved.
//

#import "AddressListViewController.h"
#import "AddAddressViewController.h"
#import "AFNetworking.h"//主要用于网络请求方法
#import "UIKit+AFNetworking.h"//里面有异步加载图片的方法
#import "AFHTTPSessionManager.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "NavView.h"
#import "ZYButton.h"
#import "Address.h"
#import "ChangePersonSignViewController.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScale   ([UIScreen mainScreen].bounds.size.width)/750
@interface AddressListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,retain) UITableView *mainTableView;
@property (nonatomic,retain) NSMutableArray *addressArr;
@property (nonatomic,retain) ZYButton *selectBtn;
@property (nonatomic,assign) BOOL  isAdd;
@end

@implementation AddressListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //self.navigationController.navigationBarHidden = YES;
}
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setUI];
    [self request];
}
- (void) setUI
{
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"收货地址"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(backClick)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *buttonNotice = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonNotice.frame = CGRectMake(0, 0, 40, 40);
    buttonNotice.titleLabel.font = [UIFont systemFontOfSize:15];
    [buttonNotice setTitle:@"添加" forState:UIControlStateNormal];
    UIBarButtonItem *btnNoticeItem = [[UIBarButtonItem alloc]initWithCustomView:buttonNotice];
    [buttonNotice addTarget:self action:@selector(addClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnNoticeItem;
    
    //    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, kScreenW, kScreenH-64)];
    //    backgroundView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0f];
    ////    backgroundView.backgroundColor = [UIColor cyanColor];
    //    [self.view addSubview:backgroundView];
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,ScreenW , ScreenH-64) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self.view addSubview:_mainTableView];
    
}
- (void)request
{
    NSString *urlStr = [NSString stringWithFormat:@"%@/userCenter/addressList",APIYIGOU];
    
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSLog(@"77777%@",allDic);
        _addressArr = [NSMutableArray array];
        [_addressArr addObjectsFromArray:allDic[@"data"]];
        [_mainTableView reloadData];
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _addressArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell =[[NSBundle mainBundle ]loadNibNamed:@"ZYTableViewCell" owner:nil options:nil][0];
    }
    //设置cell点击背景色不变
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    Address *address = [Address mj_objectWithKeyValues:_addressArr[indexPath.section]];
    UIImageView *headerImage = [[UIImageView alloc]initWithFrame:CGRectMake(30*kScale, 30*kScale, 42*kScale, 42*kScale)];
    [headerImage setImage:[UIImage imageNamed:@"收件人图标"]];
    [cell addSubview:headerImage];
    UILabel *nameLable = [[UILabel alloc]initWithFrame:CGRectMake(92*kScale, 30*kScale, kScreenW, 42*kScale)];
    nameLable.text = address.name;
    [cell addSubview:nameLable];
    
    CGFloat phoneTextW = 120;
    CGFloat phoneW = 26*kScale;
    CGFloat phoneH = 42*kScale;
    CGFloat errorH = 26;
    UIImageView *phoneImage = [[UIImageView alloc]initWithFrame:CGRectMake(kScreenW-30*kScale-phoneTextW-20*kScale-phoneW, 30*kScale, phoneW, phoneH)];
    phoneImage.image = [UIImage imageNamed:@"手机图标"];
    [cell addSubview:phoneImage];
    UILabel *phoneNumber = [[UILabel alloc]initWithFrame:CGRectMake(kScreenW-30*kScale-phoneTextW, 30*kScale, phoneTextW, 42*kScale)];
    phoneNumber.text = address.mobile;
    [cell addSubview:phoneNumber];
    UIImageView *addressImage = [[UIImageView alloc]initWithFrame:CGRectMake(30*kScale, 92*kScale, 42*kScale, 42*kScale)];
    addressImage.image = [UIImage imageNamed:@"地址图标"];
    [cell addSubview:addressImage];
    UILabel *introdocLable = [[UILabel alloc]init];
    introdocLable.font = [UIFont systemFontOfSize:15];
    introdocLable.numberOfLines = 1;
    //        introdocLable.lineBreakMode =  NSLineBreakByTruncatingTail;
    //    introdocLable.textColor = [UIColor colorWithRed:34/255.0 green:34/255.0 blue:34/255.0 alpha:1.0];
//    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
//    style.lineSpacing = 5;
    introdocLable.text = address.address_info;
//    CGSize introSize = [introdocLable sizeThatFits:CGSizeMake(kScreenW-122*kScale, MAXFLOAT)];
    
    //        NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSParagraphStyleAttributeName:style};
    //        introdocLable.attributedText = [[NSAttributedString alloc]initWithString:introdocLable.text attributes:attributes];
    
    
    introdocLable.frame = CGRectMake(30*kScale+42*kScale+20*kScale,92*kScale,kScreenW-122*kScale, 42*kScale);
    //    introdocLable.backgroundColor = [UIColor redColor];
    [cell addSubview:introdocLable];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 164*kScale, kScreenW, 2*kScale)];
    lineView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0f];
    [cell addSubview:lineView];
    ZYButton *boolSelectBtn = [ZYButton buttonWithType:UIButtonTypeCustom];
    boolSelectBtn.address = address;
    if ([address.is_default isEqualToString:@"1"]) {
        boolSelectBtn.selected = YES;
    }
    boolSelectBtn.cell = cell;
    boolSelectBtn.frame = CGRectMake(30*kScale, (224-errorH)*kScale, 42*kScale, 42*kScale);
    [boolSelectBtn setImage:[UIImage imageNamed:@"nocheck"] forState:UIControlStateNormal];
    [boolSelectBtn setImage:[UIImage imageNamed:@"选择默认地址图标"] forState:UIControlStateSelected];
    [boolSelectBtn addTarget:self action:@selector(setDefault:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:boolSelectBtn];
    UILabel *setLable = [[UILabel alloc]initWithFrame:CGRectMake(30*kScale+42*kScale+20*kScale, (224-errorH)*kScale, kScreenW, 42*kScale)];
    setLable.text = @"设置为默认";
    [cell addSubview:setLable];
    ZYButton *bianJiBtn = [[ZYButton alloc]initWithFrame:CGRectMake(kScreenW-30*kScale-240*kScale-20*kScale, (218-errorH)*kScale, 120*kScale,54*kScale)];
    bianJiBtn.layer.cornerRadius  = 8*kScale;
    bianJiBtn.layer.masksToBounds = YES;
    bianJiBtn.layer.borderWidth = 1.0f;
    bianJiBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [bianJiBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [bianJiBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [bianJiBtn addTarget:self action:@selector(bianjiClick:) forControlEvents:UIControlEventTouchUpInside];
    bianJiBtn.address = address;
    [cell addSubview:bianJiBtn];
    ZYButton *removeBtn = [[ZYButton alloc]initWithFrame:CGRectMake(kScreenW-30*kScale-120*kScale, (218-errorH)*kScale, 120*kScale, 54*kScale)];
    removeBtn.layer.cornerRadius  = 8*kScale;
    removeBtn.layer.masksToBounds = YES;
    removeBtn.layer.borderWidth = 1.0f;
    removeBtn.address = address;
    removeBtn.tag = indexPath.section;
    removeBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [removeBtn setTitle:@"删除" forState:UIControlStateNormal];
    [removeBtn addTarget:self action:@selector(removeClick:) forControlEvents:UIControlEventTouchUpInside];
    [removeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cell addSubview:removeBtn];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [[NSNotificationCenter defaultCenter] postNotificationName:MSGSELECTADDRESS object:nil];
    [DataCenter sharedDataCenter].purchaseAddress = [Address mj_objectWithKeyValues:_addressArr[indexPath.section]];
    [self backClick];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  (294-26)*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return  0.01;
    }
    return 20*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (void) setDefault:(ZYButton*)sender
{
    
    NSString *urlStr = [[NSString stringWithFormat:@"%@/userCenter/SzDefaddress?address_id=%@",APIYIGOU,sender.address.address_id]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        [sender setImage:[UIImage imageNamed:@"选择默认地址图标"] forState:UIControlStateNormal];
        [self request];
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
    
    
}
- (void)addClick
{
    _isAdd = YES;
    AddAddressViewController *addAddress = [[AddAddressViewController alloc]init];
    addAddress.isAdd = _isAdd;
    [self.navigationController pushViewController:addAddress animated:YES];
}
- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)bianjiClick:(ZYButton*)sender
{
    _isAdd = NO;
    AddAddressViewController *addAddress = [[AddAddressViewController alloc]init];
    addAddress.isAdd = _isAdd;
    addAddress.address = sender.address;
    [self.navigationController pushViewController:addAddress animated:YES];
}
- (void)removeClick:(ZYButton*)sender
{
    NSString *urlStr = [[NSString stringWithFormat:@"%@/userCenter/delectddress?address_id=%@",APIYIGOU,sender.address.address_id]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSLog(@"77777%@",allDic);
        [_addressArr removeObjectAtIndex:sender.tag];
        
        [_mainTableView reloadData];
    } error:^(YTKBaseRequest *request) {
        
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];

}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
